package com.teamc.team.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.teamc.team.entity.User;
import com.teamc.team.mapper.UserMapper;
import com.teamc.team.service.ILinkService;
import com.teamc.team.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teamc.team.vo.AdminUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ding
 * @since 2021-06-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ILinkService linkService;

    @Override
    public Boolean isRegister(String id) {
        return userMapper.haveIt(id);
    }

    @Override
    public boolean loginIsTrue(String id, String password) {
        return userMapper.haveThisAccount(id,password);
    }

    @Override
    public boolean register(String account, String password) {
        return userMapper.addUser(account,password);
    }

    @Override
    public int ChangeUserEnable(String id) {
        UpdateWrapper<User> upd = new UpdateWrapper<>();
        upd.eq("user_id",id).set("user_enabled",0);
        return userMapper.update(null,upd);
    }

    @Override
    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    @Override
    public List<AdminUserVO> findAllWithClass() {
        return userMapper.listAllUser();
    }

    @Override
    public List<AdminUserVO> findAllWithClassbyEnable() {
        return findAllWithClass().stream().filter(x -> x.getUserEnabled()!=0).collect(Collectors.toList());
    }


    @Override
    public List<AdminUserVO> findAllWithClassByID(String ID) {
        return findAllWithClass().stream().filter(x->x.getUserId().equals(ID)).collect(Collectors.toList());
    }

    @Override
    public int deleteUser(String id) {
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("user_id",id);
        return userMapper.deleteByMap(stringObjectMap);
    }

    @Override
    public int addUser(User x) {
        return userMapper.insert(x);
    }

    @Override
    public int modifyUser(User x) {
        return userMapper.updateById(x);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteUserById(String id) {
        linkService.deleteLinkByName(id);
        this.deleteUser(id);
        return true;
    }
}
